#!/usr/bin/python2.4


import common
from autotest_lib.client.common_lib import host_protections

import constants
import db_object
import host
import rpc_stubs


class TupleDbObjectWithLabels(db_object.TupleDbObject):

  __slots__ = ()

  def __getitem__(self, key):
    if key == 'labels':
      joined_labels = self['joined_labels']
      if joined_labels:
        return joined_labels.split(',')
      else:
        return []
    else:
      return super(TupleDbObjectWithLabels, self).__getitem__(key)


class Host(host.HostBase, TupleDbObjectWithLabels):

  __slots__ = ()
  KEYS = ('id', 'hostname', 'locked', 'status', 'protection_enum',
          'platform', 'joined_labels', 'idle', 'notes')
  KEY_TO_INDEX = dict((k, i) for i, k in enumerate(KEYS))

  @property
  def protection(self):
    return host_protections.Protection.get_string(self.protection_enum)

  def set_protection(self, protection):
    self.protection_enum = host_protections.Protection.get_value(protection)

  def set_notes(self, notes, commit=False):
    if commit:
      rpc_stubs.afe.set_host_attribute(constants.HA_NOTES, notes,
                                       hostname=self.hostname)
    self.notes = notes


class TestView(TupleDbObjectWithLabels):

  __slots__ = ()
  KEYS = ('test_idx', 'job_idx', 'test_name', 'reason',
          'test_started_time', 'test_finished_time',
          'job_tag', 'job_name', 'job_owner',
          'job_queued_time', 'job_started_time', 'job_finished_time',
          'hostname', 'status', 'triage_info', 'joined_labels')
  KEY_TO_INDEX = dict((k, i) for i, k in enumerate(KEYS))


class Job(TupleDbObjectWithLabels):

  __slots__ = ()
  KEYS = ('job_idx', 'job_tag', 'job_name', 'job_owner', 'hostname',
          'job_queued_time', 'job_started_time', 'job_finished_time',
          'triage_info', 'joined_labels')
  KEY_TO_INDEX = dict((k, i) for i, k in enumerate(KEYS))


class Test(db_object.TupleDbObject):

  __slots__ = ()
  KEYS = ('test_idx', 'job_idx', 'test_name', 'status', 'reason',
          'test_started_time', 'test_finished_time')
  KEY_TO_INDEX = dict((k, i) for i, k in enumerate(KEYS))
